<template>
	<router-view v-slot="{ Component }">
		<transition
			:name="transitionName"
			@before-enter="beforeEnter"
			@after-leave="afterLeave"
		>
			<keep-alive :include="virualTaskStack">
				<component
					:class="{ 'fixed top-0 left-0 w-screen z-50': isAnimation }"
					:is="Component"
					:key="$route.fullPath"
				/>
			</keep-alive>
		</transition>
	</router-view>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'

const router_type_menu = ['none', 'push', 'back']
const props = defineProps({
	routeType: {
		type: String,
		default: 'none',
		validator: (val) => {
			const res = ['none', 'push', 'back'].includes(val)
			if (!res) {
				throw new Error('routeType must be none or push or back')
			}
			return res
		},
	},
	mainComponentName: String,
})

const transitionName = ref('')
const router = useRouter()

// 虚拟任务栈的数组，用来表示栈操作
const virualTaskStack = ref([props.mainComponentName])

router.beforeEach((to, from) => {
	transitionName.value = props.routeType

	if (props.routeType === 'push') {
		// 入栈
		virualTaskStack.value.push(to.name)
	} else if (props.routeType === 'back') {
		// 出栈
		virualTaskStack.value.pop()
	}

	// 进入了首页，默认清空栈
	if (to.name === props.mainComponentName) {
		clearTaskStack()
	}
})

const isAnimation = ref(false)
const beforeEnter = () => {
	isAnimation.value = true
}

const afterLeave = () => {
	isAnimation.value = false
}

// 清空栈
const clearTaskStack = () => {
	virualTaskStack.value = [props.mainComponentName]
}
</script>

<style scoped lang="scss">
.push-enter-active {
	animation-name: push-in;
	animation-duration: 0.5s;
}

.push-leave-active {
	animation-name: push-out;
	animation-duration: 0.5s;
}

@keyframes push-in {
	0% {
		transform: translateX(50%);
	}
	100% {
		transform: translateX(0);
	}
}

@keyframes push-out {
	0% {
		transform: translateX(0);
	}
	100% {
		transform: translateX(-50%);
	}
}

.back-enter-active {
	animation-name: back-in;
	animation-duration: 0.5s;
}

.back-leave-active {
	animation-name: back-out;
	animation-duration: 0.5s;
}

@keyframes back-in {
	0% {
		transform: translateX(-50%);
	}
	100% {
		transform: translateX(0);
	}
}

@keyframes back-out {
	0% {
		transform: translateX(0);
	}
	100% {
		transform: translateX(50%);
	}
}
</style>
